// heartbeat_model.h
#ifndef HEARTBEAT_MODEL_H
#define HEARTBEAT_MODEL_H

#include <QAbstractListModel>
#include <QString>
#include <QMutex>
#include <vector>

struct HeartbeatData {
    QString robotType;
    QString robotId;
    uint64_t timestamp_ms = 0;  // 统一使用毫秒时间戳
    bool lastOnlineState;   // 状态缓冲，减少UI刷新
    QString status;  // "working"/"idle"/"charging"
    int battery;     // 电量百分比
    double x, y;     // 机器人坐标
    QString robotIP; // 机器人jetson控制板IP
    QString seerIP;  // SRC2000盒子IP
    QString cameraUrl;   // 网络相机Url
    QString currentTarget; // 当前导航目标
    QStringList capabilities; // 机器人功能类型列表，如 ["inspection", "spraying"]
};

class HeartbeatModel : public QAbstractListModel {
    Q_OBJECT

public:
    enum Roles {
        RobotTypeRole = Qt::UserRole + 1,
        RobotIdRole,
        TimestampRole,
        IsOnlineRole, 
        StatusRole,
        BatteryRole,
        RobotIPRole,
        SeerIPRole,
        CameraIPRole,
        CurrentTargetRole,
        CapabilitiesRole
    };

    explicit HeartbeatModel(QObject *parent = nullptr);
    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role) const override;
    void updateHeartbeat(const QString &robotType,
         const QString &robotId,
         uint64_t timestamp_us,
         const QString &status,
         int battery, 
         double x,
         double y,
         const QString &robotIP, 
         const QString &seerIP, 
         const QString &cameraUrl, 
         const QString &currentTarget,
         const QStringList &capabilities);
    QHash<int, QByteArray> roleNames() const override;
    bool isRobotOnline(uint64_t lastTimestampMs, uint64_t timeoutMs) const;

public slots:
    void checkTimeoutSlot(int timeoutSeconds);
    void handleHeartbeatSlot(const QVariantMap &robotData);

signals:
    // 向RobotMonitorPage.qml发送机器人状态信息
    void robotStatusUpdated(const QString &robotId, const QString &status, 
                           const QString &currentTarget, int battery, 
                           double x, double y);

private:
    mutable QMutex mutex_;
    QVector<HeartbeatData> heartbeats_;
    void ensureRobotDirectories(const QString &robotId);
};
#endif // HEARTBEAT_MODEL_H